/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.Actions;

import dao.SubGroupAccountDAO;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Erro;
import model.SubGroupAccount;
import model.User;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author adriano.lourenco
 */
public class SubGroupAccountAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {

            User u = (User) request.getSession().getAttribute("User");
            if (u == null) {
                request.getSession().setAttribute("ErroMSG", Erro.erroMsg[Erro.NAO_AUTENTICADO]);
                return mapping.findForward("erroAlias");
            } else {

                SubGroupAccountDAO gpDAO = new SubGroupAccountDAO();

                String key = request.getParameter("key");
                ArrayList<SubGroupAccount> listaSubGrupoDeContas = gpDAO.readByKey(key);

                JSONArray array = new JSONArray();

                for (SubGroupAccount listaSubGrupoDeConta : listaSubGrupoDeContas) {
                    JSONObject object = new JSONObject();

                    object.put("id", listaSubGrupoDeConta.getId());
                    object.put("descricao", listaSubGrupoDeConta.getDescricao());

                    array.put(object);
                }

                String jsonResult = array.toString();
                response.setContentType("text/javascript; charset=utf-8");
                response.getWriter().write(jsonResult);
                gpDAO.closeDAO();

//                request.getSession().setAttribute("ListSubGroupAccount", listaSubGrupoDeContas);

//                return mapping.findForward("PlanGroupAlias");
                return null;
            }

        } catch (Exception e) {
            return mapping.findForward("erroAlias");
        }
    }

}
